package com.kischang.blog.utils;

import com.kischang.blog.model.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class CookieUtils {

	/**
	 * cookie的增加、删除、查询
	 */
	public static final String USER_COOKIE = "user.cookie";

	// 创建一个cookie
	public static Cookie createCookie(User user,int day) {
		Cookie cookie = new Cookie(USER_COOKIE,user.getUsername()+"|"+Utils.createUUID());
		cookie.setMaxAge(60 * 60 * 24 * day);// cookie保存时间
		return cookie;
	}

	// 得到cookie
	public static String getCookieValue(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (CookieUtils.USER_COOKIE.equals(cookie.getName())) {
					return new String(cookie.getValue().getBytes());
				}
			}
		}
		return null;
	}
	public static Cookie getCookie(HttpServletRequest request,String cookiename) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookiename.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}

	// 删除指定cookie
	public static Cookie delCookie(HttpServletRequest request,String key) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (key.equals(cookie.getName())) {
					cookie.setValue("");
					cookie.setMaxAge(0);
					return cookie;
				}
			}
		}
		return null;
	}


}
